package com.ca.ridersclubapplication.view.bar;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.ca.ridersclubapplication.R;

public class MiniLineProcessBar extends ConstraintLayout {

    private float ratio;
    private Drawable lineBackground;

    public ConstraintLayout line;

    public MiniLineProcessBar(@NonNull Context context) {
        super(context);
        initView(context, null);
    }

    public MiniLineProcessBar(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }

    public MiniLineProcessBar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attrs) {

        View view = LayoutInflater.from(context).inflate(R.layout.mini_line_process_bar_layout, this);
        line = view.findViewById(R.id.line);

        if (attrs != null) {
            TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MiniLineProcessBar, 0, 0);

            ratio = array.getFloat(R.styleable.MiniLineProcessBar_mlpb_ratio, 0);
            lineBackground = array.getDrawable(R.styleable.MiniLineProcessBar_mlpb_lineBackground);

            array.recycle();
        }

        setRatio(ratio);
        setLineBackground(lineBackground);
    }

    public float getRatio() {
        return ratio;
    }

    public void setRatio(float ratio) {

        this.ratio = ratio < 0 ? 0 : ratio;

        post(() -> {
            int parentWidth = getWidth();

            int lineWidth = (int) (parentWidth * this.ratio);
            ViewGroup.LayoutParams params = this.line.getLayoutParams();
            params.width = lineWidth;
            this.line.setLayoutParams(params);
        });
    }

    public Drawable getLineBackground() {
        return lineBackground;
    }

    public void setLineBackground(Drawable lineBackground) {
        this.lineBackground = lineBackground;
        line.setBackground(lineBackground);
    }
}
